import os
import requests
from tkinter import Tk, Label, Button, Entry, filedialog
from PIL import Image, ImageFilter, ImageEnhance

# 你的 RemoveBG API 密钥
API_KEY = '6bQgdnR3huTbA9tDEwDEHhra'


def remove_background(image_path, output_path):
    with open(image_path, 'rb') as image_file:
        response = requests.post(
            'https://api.remove.bg/v1.0/removebg',
            files={'image_file': image_file},
            data={'size': 'auto', 'format': 'png'},  # 指定输出格式为 PNG
            headers={'X-Api-Key': API_KEY},
        )
        if response.status_code == requests.codes.ok:
            with open(output_path, 'wb') as out_file:
                out_file.write(response.content)
            print(f"已处理: {image_path}")
        else:
            print(f"错误: {response.status_code}, {response.text}")


def add_shadow(input_path, output_path):
    image = Image.open(input_path).convert('RGBA')
    shadow = Image.new('RGBA', image.size, color=(0, 0, 0, 0))
    shadow.paste(image, (10, 10), image)  # 偏移量为 (10, 10)
    shadow = shadow.filter(ImageFilter.GaussianBlur(5))  # 高斯模糊处理阴影
    combined = Image.alpha_composite(shadow, image)
    combined.save(output_path)


def apply_highlight_filter(image_path, output_path):
    image = Image.open(image_path).convert('RGBA')

    # 应用高亮滤镜
    enhancer = ImageEnhance.Brightness(image)
    bright_image = enhancer.enhance(1.2)  # 1.2 是亮度增强系数，可以调整

    # 保存最终图像
    bright_image.save(output_path)


def process_images(input_folder):
    output_folder = os.path.join(input_folder, 'output')
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('png', 'jpg', 'jpeg')):
            input_path = os.path.join(input_folder, filename)
            output_filename = os.path.splitext(filename)[0] + '.png'
            temp_output_path = os.path.join(output_folder, 'temp_' + output_filename)
            final_output_path = os.path.join(output_folder, output_filename)

            remove_background(input_path, temp_output_path)
            add_shadow(temp_output_path, temp_output_path)  # 在临时文件上添加阴影
            apply_highlight_filter(temp_output_path, final_output_path)  # 添加高亮滤镜
            os.remove(temp_output_path)

    print(f"所有图片处理完成，已保存到 {output_folder}")


def select_input_folder():
    folder_selected = filedialog.askdirectory()
    if folder_selected:
        input_path_entry.delete(0, 'end')
        input_path_entry.insert(0, folder_selected)


def start_processing():
    input_folder = input_path_entry.get()
    if os.path.isdir(input_folder):
        process_images(input_folder)
    else:
        print("请输入有效的文件夹路径")


# 创建主窗口
root = Tk()
root.title("图片去背景、添加阴影和高亮滤镜")

# 输入路径标签和文本框
input_path_label = Label(root, text="输入文件夹路径:")
input_path_label.grid(row=0, column=0, padx=10, pady=10)

input_path_entry = Entry(root, width=50)
input_path_entry.grid(row=0, column=1, padx=10, pady=10)

# 浏览按钮
browse_button = Button(root, text="浏览", command=select_input_folder)
browse_button.grid(row=0, column=2, padx=10, pady=10)

# 开始处理按钮
start_button = Button(root, text="开始处理", command=start_processing)
start_button.grid(row=1, column=0, columnspan=3, pady=20)

# 运行主循环
root.mainloop()
